import Vue from 'vue'
import Vuex from 'vuex'
// import { Login,  GetMenuList, GetAllMenuList } from "@/api/index";
import { Login } from "@/api/index";
// import common from "../utils/common";
import router from "../router";
// import routes from "../router/routes";
import { filterRoutes } from "../router/whiteList";
import { Message } from 'element-ui'
import loadSystem from "../loadSystem"
// import installPrototypeData from '@/utils/installPrototypeData'

Vue.use(Vuex)

const loginFn = (res, context, resolve, reject) => {
  if (res.IsSuccess) {
    if (res.NeedSecondAuthentication) {
      resolve(true)
    } else {
      localStorage.setItem('userInfo', JSON.stringify(res.LoginInfo));
      // Vue.use(installPrototypeData);
      context.state.Tabs = [];
      Message({
        message: '登录成功！',
        type: 'success',
        showClose: true,
      })
      resolve(false)
    }
  } else {
    Message({
      message: res.ErrorMessage,
      type: 'error',
      duration: res.ErrorMessage.includes('锁定') ? 10 * 1000 : 3000
    })
    reject()
  }
}

export default new Vuex.Store({
  state: {
    AllRoutes: [],     // 全部后端返回路由 
    MenuList: [],       // 菜单栏数组(所有菜单栏)
    Tabs: [],       // 卡片数组
    CurrPermissionUI: [],      //  当前系统有权限的路由数组
    AllPermissionUI: [],    // 所有有权限的ui资源
    DiffState: "disable",               // menu菜单是显示隐藏模式还是禁用不禁用模式     show：显示隐藏模式    disable：禁用不禁用模式
  },

  getters: {

  },

  mutations: {
    updateTabs(state, { to, type }) {
      if (to.name === null) return
      state.AllRoutes.forEach(item => {
        if (item.Url == to.name) to.meta.title = item.Title;
      })
      let { name, path, meta } = to;
      let index = state.Tabs.findIndex(val => val.name == name);
      if (index >= 0) state.Tabs[index] = to;   // 编辑
      if (type == 'add' && index < 0) if (to.path != '/login' && to.name != 'error') state.Tabs.push(to);     // 添加
      if (type == 'del' && index >= 0) state.Tabs.splice(index, 1)            // 删除
    },
  },

  actions: {
    actionsLogin(context, data) {
      // 登录
      return new Promise((resolve, reject) => {
        Login(data).then(res => {
          loginFn(res, context, resolve, reject)
        }).catch(err => {
          reject((err))
        })
      })
    },
    // 二次验证登录
    actionAuthLogin(context, data) {
      return new Promise((resolve, reject) => {
        SecondAuth(data).then(res => {
          loginFn(res, context, resolve, reject)
        })
      })
    },
    actionsGetMenu(context, { systemName, toRoute }) {
      return new Promise((resolve, reject) => {
        const tagGroup = systemName ? [{ ResName: systemName, Sys: "NewSystem" }] : [{ ResName: "NewSystemBg", Sys: "NewSystem" }];
        let arr = context.state.AllRoutes.filter(val => val.Type == 0 || val.Type == 1);
        let p1 = arr.length ? Promise.resolve(context.state.AllRoutes.filter(val => val.Type == 0 || val.Type == 1)) : GetAllMenuList({
          order: "Order asc",
          select: "ID,Icon,LevelCode,Name,Order,ParentID,Title,Type,Url",
          where: "1=1 and Sys='NewSystem' and IsEnable=1"
        }).then(res => {
          arr = res.filter(val => val.Type == 0 || val.Type == 1);
          context.state.AllRoutes = res.filter(val => val.Type == 0 || val.Type == 1);
        })
        let p2 = GetMenuList({
          tagGroup
        }).then(res => {
          const resName = systemName || 'NewSystemBg';
          const find = res.find(val => val.Tag.ResName == resName);
          const groups = find ? find.ChildGroup : [];
          context.state.CurrPermissionUI = groups;
          context.state.AllPermissionUI = [...context.state.AllPermissionUI, ...groups].filter(val => val.Type == 0 || val.Type == 1);
        })
        Promise.all([p1, p2]).then(() => {
          Vue.use(installPrototypeData);
          if (!!systemName) {
            const clone = JSON.parse(JSON.stringify(context.state.CurrPermissionUI));
            const roleList = clone.filter(val => val.Type && val.Type != 2).map(key => key = { Url: key.Url = `/${systemName}/` + key.Url });
            const loadSystemFn = loadSystem(Vue, router);
            loadSystemFn(systemName, roleList).then(_ => resolve());
          } else {
            const index = router.getRoutes().findIndex(val => val.path == toRoute);
            if (index >= 0) return;     // 如果当前跳转的路由已经注册，就不用再执行注册了，避免重复注册警告
            const roleList = context.state.CurrPermissionUI.filter(val => val.Type && val.Type != 2).map(key => key.Url);
            filterRoutes(routes, roleList).forEach(item => router.addRoute('layout', item));
          }
          context.state.MenuList = context.state.DiffState == 'disable' ? common.menuToTree(arr) : context.state.DiffState == 'show' ? common.menuToTree(context.state.AllPermissionUI) : [];
          if (!systemName) resolve(context.state.MenuList)
        }).catch(_ => {
          reject()
        })
      })
    }
  }
}) 